<!DOCTYPE html>  
<html>
<meta charset="utf-8" />  
<title>js基本算法</title>  
<body>
<h2>js基本算法</h2>  
</body>
<script>
    const arr = [3,2,15,7,1,5];
    // 冒泡算法
    function bubbleSort(arr){
        var l = arr.length;
        for(let i=0;i<l-1;i++){
            for(let j=i+1;j<l;j++){
                if(arr[i]>arr[j]){
                    var t = arr[i];
                    arr[i] = arr[j];
                    arr[j] = t;
                }
            }
        }
        return arr;
    }
    console.log('bubbleSort',bubbleSort(arr))

    // 快速排序
    function quickSort(arr){
        var l = arr.length;
        if(l<=1){
            return arr;
        }
        let leftArry = [];
        let rightArry = [];
        let firstNum = arr[0];

        for(let i=1;i<l;i++){
            if(arr[i]>firstNum){
                rightArry.push(arr[i])
                
            }else{
                leftArry.push(arr[i])
            }
        }
        return [].concat(quickSort(leftArry),[firstNum],quickSort(rightArry));
    }
    console.log('quickSort',quickSort(arr))

    // 插入排序
    function insertionSort(arr) {
        var len = arr.length;
        var preIndex, current;
        for (var i = 1; i < len; i++) {
            preIndex = i - 1;
            current = arr[i];
            while(preIndex >= 0 && arr[preIndex] > current) {
                arr[preIndex+1] = arr[preIndex];
                preIndex--;
            }
            arr[preIndex+1] = current;
        }
        return arr;
    }
    console.log('insertionSort',insertionSort(arr))

    // 选择排序
    function selectionSort(arr) {
        var len = arr.length;
        var minIndex, temp;
        for (var i = 0; i < len - 1; i++) {
            minIndex = i;
            for (var j = i + 1; j < len; j++) {
                if (arr[j] < arr[minIndex]) {     // 寻找最小的数
                    minIndex = j;                 // 将最小数的索引保存
                }
            }
            temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
        return arr;
    }
    console.log('selectionSort',selectionSort(arr))
    
</script>
</html>